package com.lagou.controller;

import com.github.pagehelper.PageInfo;
import com.lagou.common.RequestPage;
import com.lagou.common.ResponseResult;
import com.lagou.entity.LagouUser;
import com.lagou.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Api(value = "/user", description = "用户服务")
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "注册接⼝，true成功，false失败", httpMethod = "POST", produces = "application/json")
    @PostMapping(value = "/register/{email}/{password}/{code}")
    @ResponseBody
    public ResponseResult<Boolean> register(@PathVariable String email, @PathVariable String password, @PathVariable String code) {
        return ResponseResult.success(userService.register(email, password, code));
    }

    @ApiOperation(value = "是否已注册，根据邮箱判断,true已注册，false尚未注册", httpMethod = "POST", produces = "application/json")
    @PostMapping(value = "/isRegistered/{email}")
    @ResponseBody
    public ResponseResult<Boolean> isRegister(@PathVariable String email) {
        return ResponseResult.success(userService.isRegistered(email));
    }

    @ApiOperation(value = "登录接⼝，登录成功返回邮箱地址，重定向到欢迎⻚", httpMethod = "POST", produces = "application/json")
    @RequestMapping(value = "/login/{email}/{password}", method = RequestMethod.POST)
    public void login(@PathVariable String email, @PathVariable String password, HttpServletResponse response) throws IOException {
        String token = userService.login(email, password);
        /**
         * 目前一般使用header, 以便于同时支持浏览器和app
         */
        response.addHeader("Authorization", token);
        response.addCookie(new Cookie("token", token));
        /**
         * 由于mac不允许使用80端口, 这里使用9000作为nginx端口
         */
        response.sendRedirect("http://127.0.0.1:9000/welcome.html");
    }


    @ApiOperation(value = "根据token查询⽤户登录邮箱接⼝", httpMethod = "GET", produces = "application/json")
    @GetMapping(value = "/info/{token}")
    @ResponseBody
    public ResponseResult<String> getEmail(@PathVariable String token) {
        return ResponseResult.success(userService.getEmail(token));
    }

    @ApiOperation(value = "用户分页列表", httpMethod = "POST", produces = "application/json")
    @PostMapping(value = "/list")
    @ResponseBody
    public ResponseResult<PageInfo<LagouUser>> getPageList(@Validated RequestPage<Object> requestPage) {
        return ResponseResult.success(userService.getUserList(requestPage));
    }
}
